from fastapi import FastAPI, HTTPException, Body
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from pptx import Presentation
import json
import uuid
import os

app = FastAPI()
OUTPUT_DIR = "/app/src/generated_ppts"  # 更新为容器内路径

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class PPTRequest(BaseModel):
    title: str
    slides: list

@app.post("/generate-ppt")
async def generate_ppt(request: PPTRequest):
    try:
        # 直接解析原始内容（Dify 应确保传递合法 JSON）
        data = request.model_dump()
        print(data)
        return await _generate_ppt(data)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/generate-ppt-from-str")
async def generate_ppt_from_str(request_data: str = Body(..., media_type="text/plain")):
    try:
        # 解析字符串格式的JSON
        data = json.loads(request_data)
        if not isinstance(data, dict):
            raise ValueError("Invalid JSON structure")
        return await _generate_ppt(data)
    except json.JSONDecodeError as e:
        raise HTTPException(status_code=400, detail=f"Invalid JSON: {str(e)}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def _generate_ppt(data: dict):
    ppt_id = str(uuid.uuid4())
    output_file = os.path.join(OUTPUT_DIR, f"{ppt_id}.pptx")
    prs = Presentation()

    # 封面页
    slide = prs.slides.add_slide(prs.slide_layouts[0])
    slide.shapes.title.text = data["title"]
    slide.placeholders[1].text = data["slides"][0]["content"]

    # 其他页
    for slide_data in data["slides"][1:]:
        slide = prs.slides.add_slide(prs.slide_layouts[1])
        slide.shapes.title.text = slide_data["slide_title"]
        slide.placeholders[1].text = slide_data["content"]

    prs.save(output_file)
    return {"download_url": f"http://192.168.1.100:8000/download-ppt/{ppt_id}"}  # 使用容器名而非 IP

@app.get("/download-ppt/{ppt_id}")
async def download_ppt(ppt_id: str):
    file_path = os.path.join(OUTPUT_DIR, f"{ppt_id}.pptx")
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="File not found")
    return FileResponse(file_path, filename="presentation.pptx")

@app.get("/")
async def root():
    return {"message": "PPT Generator API is running"}